let socketTask = null
let isConnected = false
let isManuallyClosed = false
let reconnectTimer = null
let reconnectCount = 0
let onMessageCallback = null
let urlCache = ''
let hasBind = false

// 最大重连次数 - 设成无限你就等于无敌
const MAX_RECONNECT = Infinity
const RECONNECT_INTERVAL = 5000

const connect = (url, messageHandler) => {
	if (!url || isConnected) return

	urlCache = url
	onMessageCallback = messageHandler
	isManuallyClosed = false

	console.log(`🚀 正在连接 WebSocket -> ${url}`)
	socketTask = uni.connectSocket({ 
		url:url,
		header:{
			'Authorization': 'Bearer ' + uni.getStorageSync('token1')
		}
		
	})

	if (!hasBind) {
		uni.onSocketOpen(handleOpen)
		uni.onSocketMessage(handleMessage)
		uni.onSocketClose(handleClose)
		uni.onSocketError(handleError)
		hasBind = true
	}
}

const handleOpen = () => {
	console.log('✅ WebSocket 已连接')
	isConnected = true
	reconnectCount = 0
}

const handleMessage = (res) => {
	try {
		const data = JSON.parse(res.data)
		console.log('📩 收到消息：', data)
		onMessageCallback && onMessageCallback(data)
	} catch (e) {
		console.error('❌ 消息解析失败', e)
	}
}

const handleClose = () => {
	console.warn('🔌 WebSocket 已关闭')
	isConnected = false
	if (!isManuallyClosed) tryReconnect()
}

const handleError = (err) => {
	console.error('💥 WebSocket 错误:', err)
	if (!isManuallyClosed) tryReconnect()
}

const tryReconnect = () => {
	if (reconnectCount >= MAX_RECONNECT) {
		console.warn('⛔ 已达到最大重连次数')
		return
	}
	reconnectTimer && clearTimeout(reconnectTimer)
	reconnectTimer = setTimeout(() => {
		reconnectCount++
		console.log(`♻️ 第 ${reconnectCount} 次尝试连接 WebSocket`)
		connect(urlCache, onMessageCallback)
	}, RECONNECT_INTERVAL)
}

const send = (data) => {
	if (!isConnected) {
		console.warn('⛔ WebSocket 未连接，无法发送消息')
		return {
			success: false,
			message: 'WebSocket 未连接'
		}
	}

	try {
		uni.sendSocketMessage({
			data: JSON.stringify(data),
			success: () => {
				console.log('📤 消息发送成功:', data)
			},
			fail: (err) => {
				console.error('❌ 消息发送失败:', err)
			}
		})
		return { success: true }
	} catch (e) {
		console.error('🚫 发送异常:', e)
		return { success: false, message: '发送异常' }
	}
}

const close = () => {
	console.log('🛑 主动关闭 WebSocket')
	isManuallyClosed = true
	isConnected = false
	clearTimeout(reconnectTimer)
	uni.closeSocket()
}

const getConnectionStatus = () => isConnected

export default {
	connect,
	send,
	close,
	getConnectionStatus
}
